<template>
  <div class="feedBack">
    <van-nav-bar
        :title="$t('problem_feedback')"
        left-arrow
        @click-left="$router.go(-1)"
    />
    <div class="feed_back_box">
      <div class="box_item">
        <van-field
            v-model="value"
            rows="4"
            autosize
            type="textarea"
            maxlength="500"
            mi
            :placeholder="$t('problem_describe')"
            show-word-limit
        >
          <template #left-icon>
            <div class="upload">
              <van-uploader style="width: 100%;height: 100%;" v-model="fileList" multiple :before-read="beforeRead"
                            :max-count="1"/>
            </div>
          </template>
        </van-field>
      </div>
    </div>
    <div class="confirm">
      <button @click="confirm">{{ $t('finish') }}</button>
    </div>
  </div>
</template>

<script>
import {ref} from "vue";
import {addFeedBack} from '@/api/my'
import {Toast} from "vant";
import {useI18n} from 'vue-i18n'
import router from "@/router";
import {compressImage, debounce} from '@/utils/tool'
import {useStore} from "vuex";
export default {
  setup() {
    const value = ref('')
    const fileList = ref([])
    const store = useStore()
    const {tm} = useI18n()
    const beforeRead = (file) => {
      return new Promise(async (resolve, reject) => {
        const fileType = ['image/jpeg', 'image/png', 'image/jpg']
        if (fileType.indexOf(file.type) === -1) {
          Toast('upload_image');
          reject()
        } else if (file.size < Math.pow(1024, 2)) {
          // 小于1m不压缩
          resolve(file)
        } else {
          // 压缩图片
          const caseFile = await compressImage(file)
          resolve(caseFile)
        }
      })
    }
    const confirm = debounce(
        async () => {
          if (value.value.length < 5) return Toast({message:tm('problem_feedback_len')})
          const file = fileList.value.length ? fileList.value[0].file : ''
          const formData = new FormData()
          formData.append('file', file)
          formData.append('content', value.value)
          const res = await addFeedBack(formData)
          if (res.code === 1) {
            Toast({
              message: tm('submit_success')
            })
            router.go(-1)
          }
        }
    )
    // 清除loading
    store.dispatch('changeLoading', false)
    return {
      value,
      beforeRead,
      fileList,
      confirm
    }
  }
}
</script>

<style scoped lang="less">
.feedBack {
  background-color: #f2f3f5;
  overflow: auto;

  .van-picker__confirm {
    color: #FF5252 !important;
  }

  ::v-deep .van-nav-bar {
    background: linear-gradient(90deg, #FF5252, #FF8244) !important;
    z-index: 1999;
  }

  ::v-deep .van-nav-bar .van-icon {
    color: #333333 !important;
  }

  .feed_back_box {
    padding: 10px;

    .box_item {
      background-color: #FFFFFF;

    }
  }
}
</style>
